<template>
	<view class="login-wrap">
		<up-form ref="loginFormRef" labelWidth='0' :model="loginForm" :rules="rules">
			<up-form-item borderBottom prop="phone">
				<up-input placeholder="请输入手机号" border="none" v-model="loginForm.phone"></up-input>
			</up-form-item>
			<up-form-item borderBottom prop="code">
				<up-input placeholder="请输入验证码" border="none" v-model="loginForm.code">
					<template #suffix>
						<up-code ref="uCodeRef" startText="点击获取验证码" @change="codeChange" seconds="20" changeText="X秒后重新获取"></up-code>
						<text @tap="getCode">{{tips}}</text>
					</template>
				</up-input>
			</up-form-item>
		</up-form>
		<up-button @click="doLogin" type="primary">登录</up-button>
	</view>
</template>

<script setup>
	import { debounce } from 'uview-plus';
	import {
		ref
	} from 'vue';
import { DO_LOGIN, GET_PHONE_CODE } from '../../api/phonelogin';

	const loginForm = ref({
		phone: '',
		code: ''
	})
	const loginFormRef = ref(null)
	const tips = ref('')
	const rules = ref({
		phone: {
			type: 'string',
			required: true,
			message: '请输入手机号',
			trigger: ['change', 'blur']
		},
		code: {
			type: 'string',
			required: true,
			message: '请输入验证码',
			trigger: ['change', 'blur']
		}
	})
	const uCodeRef = ref(null)
	const codeChange = (text) => {
		tips.value = text
	}
	const getCode = () => {
		// 判断如果当前没有处于倒计时的状态
		// 不是的话，发送验证码，并重新开始倒计时
		// 是的话， 提示已发送
		console.log('点击获取验证码了')
		if(!loginForm.value.phone) {
			uni.$u.toast('请输入手机号')
			return
		}
		if(uCodeRef.value.canGetCode) {
			// 获取验证码
			// uni.request({
			// 	url: 'http://localhost:8002/admin/sendcode',
			// 	method: 'GET',
			// 	success(res) {
			// 		console.log(res)
			// 		if(res.statusCode === 200) {
			// 			uni.setStorageSync('code', res.data.code)
			// 			uCodeRef.value.start()
			// 		} else {
						
			// 		}
					
			// 	}
			// })
			
			GET_PHONE_CODE().then(res => {
				console.log(res)
				uni.setStorageSync('code', res.code)
				uCodeRef.value.start()
			})
		} else {
			uni.$u.toast('验证码已发送，请倒计时结束后重新获取')
		}
	}
	
	const doLogin = () => debounce(
		() => {
			console.log('触发了')
			loginFormRef.value.validate().then(valid => {
				console.log(valid)
				if(valid) {
					const code = uni.getStorageSync('code')
					if(loginForm.value.code === code) {
						// 掉登录接口实现登录
						DO_LOGIN(loginForm.value.phone).then(res => {
							console.log(res)
							uni.setStorageSync('token', res.token.token)
							uni.setStorageSync('phone', res.phone)
							uni.switchTab({
								url: '/pages/index/index'
							})
						})
					} else {
						uni.$u.toast('验证码输入错误')
					}
				}
			})
		},
		500
	)
</script>

<style lang="scss" scoped>
	.login-wrap {
		width: 80vw;
		margin: 0 auto;
	}
</style>